<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document</title>
    <style>
        .list {
            width: 200px;
            background-color: rgb(184, 173, 184);
            height: 150px;
            overflow: auto;
        }

        .news {
            width: 100%;
            height: 30px;
        }
    </style>
</head>

<body>
    <!-- 准备一个“容器” -->
    <div id="test"></div>

    <!-- 引入 react 核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入 react-dom. 用于支持 react 操作 dom -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入babel. 用于将 jsx 转换为 js -->
    <script src="../js/babel.min.js"></script>
    <script type="text/babel"> /* 这里必须写 babel */
        // 创建 DOM
        class NewsList extends React.Component {
            state = { newsArr: [] }

            componentDidMount() {
                setInterval(() => {
                    console.log("componentDidMount")
                    const { newsArr } = this.state;
                    const news = "新闻" + (newsArr.length + 1)
                    this.setState({ newsArr: [news, ...newsArr] })
                }, 1000)
            }

            getSnapshotBeforeUpdate(){
                return this.refs.list.scrollHeight
            }

            componentDidUpdate(preProps,preState,height){
                this.refs.list.scrollTop += this.refs.list.scrollHeight - height
            }

            render() {
                const { newsArr } = this.state;
                return (
                    <div className="list" ref="list">
                        {
                            newsArr.map((item,index) => {
                                return <div className="news" key={index}>{item}</div>
                            })
                        }
                    </div>
                )
            }
        }
        // 渲染 DOM
        ReactDOM.render(<NewsList />, document.getElementById("test"))
    </script>
</body>

</html>